//
//  DepartureWalker.m
//  TrainTrack
//
//  Created by Philip Bruce on 4/10/08.
//  Copyright 2008 Den Falske Zebra. All rights reserved.
//

#import "DepartureWalker.h"
#import "Departure.h"

@implementation DepartureWalker

+(NSMutableArray *)findValidDepartures:(NSArray *)departures {
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
	[dateFormatter setDateFormat:@"H"];
	// get the current hour
	NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
	int hour = [dateString intValue];
	// get the current minute
	[dateFormatter setDateFormat:@"mm"];
	dateString = [dateFormatter stringFromDate:[NSDate date]];
	int minute = [dateString intValue];
	
	NSLog(@"hour: %d, minute: %d", hour, minute);
	
	NSMutableArray *validDepartures = [[NSMutableArray alloc] init];
	
	int departure_index = 0;
	// find starting point in array
	for(Departure *departure in departures) {
		if (departure.minute >= minute) {
			break;
		}
		departure_index++;
	}
	
	NSLog(@"departure_index: %d", departure_index);
	
	// iterate array
	while([validDepartures count] != 10) {
		// rollover array index and increase the hour if we have reached the end of the array
		if ([departures count] == departure_index) {
			departure_index = 0;
			hour++;
			// roll over hour if next day has been reached
			if (hour == 24) {
				hour = 0;
			}
		}
		// add the departure to the array of valid departures if it's valid
		if ([[departures objectAtIndex:departure_index] isValidForHour:hour]) {
			[validDepartures addObject:[[Departure alloc] initByCloning:[departures objectAtIndex:departure_index]]];
		}
		departure_index++;
	}
	
	return validDepartures;	
}
@end
